﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using System.Collections;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;

public partial class NewProduct : System.Web.UI.Page
{

    List<string> fields = new List<string>();
    ArrayList values = new ArrayList();
    List<string> types = new List<string>();
    /////////////////////////////////////
    List<string> fields2 = new List<string>();
    ArrayList values2 = new ArrayList();
    List<string> types2 = new List<string>();
    /////////////////////////////////////
    string auther = "";
    string title = "";
    string desc = "";
    string topic = "";
    string pups = "";
    string issn = "";
    string dwoy = "";
    string lc = "";
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
         
        if (!Page.IsPostBack)
        {
            if(!string.IsNullOrEmpty(Request.QueryString["poid"]))
            {
            ViewState.Add("paths", "");
            //GridView1.DataSource = SqlDataSource1;
            //GridView1.DataBind();
            DropDownList1.DataBind();
            DropDownList2.DataBind();
            DropDownList3.DataBind();
            DropDownList3.DataBind();
            DropDownList4.DataBind();
            DropDownList5.DataBind();

            Product p = new Product();
            p.getfromdatabase(int.Parse(Request.QueryString["poid"]));
            ViewState["aoe"] = "0";
            
            if (p.product_type_id!= 0)
            {
                
                ListItem ls = DropDownList1.Items.FindByValue(p.product_type_id.ToString());
                DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(ls);

            }
            if (p.freq_id  != 0)
            {
                DropDownList2.SelectedIndex = DropDownList2.Items.IndexOf(DropDownList2.Items.FindByValue(p.freq_id.ToString()));

            }
            if (p.classification_id !=0)
            {
                DropDownList3.SelectedIndex = DropDownList3.Items.IndexOf(DropDownList3.Items.FindByValue(p.classification_id.ToString()));

            }
            if (p.puplisher_id.ToString() != null)
            {
                DropDownList5.SelectedIndex = DropDownList5.Items.IndexOf(DropDownList5.Items.FindByValue(p.puplisher_id.ToString()));

            }
            /////////////////////////////////////////////
            isn.Text = p.issn;
            dewey.Text = p.dwoy;
            pup.Text = p.publisher;
            auth.Text = p.auther1;
            address.Text = p.product;
            notes.Text = p.productdesc;
            lcs.Text = p.lc;
            topics.Text = p.topic;

            var pf = p.ProductFields.Where(o => o.tag == "000");
            if (pf.Count() > 0)
                leader.Text = pf.First().field;
            pf = p.ProductFields.Where(o => o.tag == "008");
            if (pf.Count() > 0)
                fix.Text = pf.First().field;
            pf = p.ProductFields.Where(o => o.tag == "300");
            if (pf.Count() > 0)
                f300.Text = pf.First().field;

            pf = p.ProductFields.Where(o => o.tag == "005");
            if (pf.Count() > 0)
                f005.Text = pf.First().field;
           

            
            Grid1.DataSource = p.ProductFields;
            Grid1.DataBind();
            ////////////////////////////////////////////

            

            Page.ClientScript.RegisterStartupScript(this.GetType(), "hj", "there();", true);
        }

        }


    }
    protected override void InitializeCulture()
    {
        if (Session["CurrentCulture"] != null)
        {
            string lang = Session["CurrentCulture"].ToString();
            if (lang != null && lang != "")
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
                Thread.CurrentThread.CurrentCulture.DateTimeFormat = new CultureInfo("en-US", false).DateTimeFormat;
                // Thread.CurrentThread.CurrentCulture.Calendar=new  System.Globalization.GregorianCalendar();

            }
        }

    }
    public void form1Mrc(string[] fs)
    {


        fields2.Add("tag");
        types2.Add("string");
        values2.Add("000");
        /////////////////////////////////////////////////

        fields2.Add("field");
        types2.Add("string");
        values2.Add(fs[0].Substring(5));
        /////////////////////////////////////////////// 
        /////////////////new///////////////////////////////

        switchs("000", fs[0].Substring(5));
        ////////////////////////////////

        Regex regex = new Regex("^(\\d{3})");
        string tag = "";
        string ind = "";
        string field = "";


        foreach (string fx in fs)
        {

            string ff = fx.Replace("=", "");
            ff = ff.Replace("\\", "");
            Match match = regex.Match(ff);
            if (match.Groups[1].Value != "")
            {
                tag = match.Groups[1].Value;
                /////////////////////////////////////////

                fields2.Add("tag");
                types2.Add("string");
                values2.Add(tag);

                /////////////////////////////////////////////////


                /////////////////////////////
                ff = ff.TrimStart(tag.ToCharArray());
                ff = ff.TrimStart();
                if (ff.Contains("$"))
                {
                    string[] mm = ff.Split("$".ToCharArray());
                    if (mm[0] != "")
                    {
                        ind = mm[0];
                        //////////////////////////////
                        fields2.Add("indicator");
                        types2.Add("string");
                        values2.Add(ind);
                        /////////////////////////////////////////////////  

                    }
                    string subs = "";
                    for (int i = 1; i < mm.Length; i++)
                    {
                        subs += mm[i].Substring(0, 1) + "$";
                        mm[i] = mm[i].Replace('"', ' ');
                        mm[i] = mm[i].Replace("'", "");
                        mm[i] = mm[i].Remove(0, 1);
                        //////////////////////////////


                        field += mm[i] + "%";
                    }
                    fields2.Add("subfield");
                    types2.Add("string");
                    values2.Add(subs.TrimEnd('$'));
                    /////////////////////////////////////////////////  
                    //////////////////////////////
                    fields2.Add("field");
                    types2.Add("string");
                    values2.Add(field.TrimEnd('%'));
                    ///////////////////////////////////////////////  
                    switchs(tag, field.Replace('%', ' '));

                }
                else
                {
                    ff = ff.Replace('"', ' ');
                    ff = ff.Replace("'", "");
                    //////////////////////////////
                    fields2.Add("field");
                    types2.Add("string");
                    values2.Add(ff);
                    //////////////////////////
                    switchs(tag, ff);
                    ///////////////////////////////////////////////////     
                    field = ff;
                }
                //Response.Write(tag + "   " + ind + "   " + field);
                //Response.Write("<br />");

            }
            tag = "";
            ind = "";
            field = "";


        }
        insertion();

    }


    public void form2Mrc(string[] fs)
    {
        //List<string> fields2 = new List<string>();
        //ArrayList values2 = new ArrayList();
        //List<string> types2 = new List<string>();
        ///////////////////////////////////////

        Regex regex2 = new Regex("^(\\t \\t\\d|\\t\\d\\t\\d|\\t\\d)");
        Regex regex = new Regex("^(\\d{3})");
        string tag = "";
        string ind = "";
        string field = "";
        ///////////////////////////////////////////
        /////////////////////////////////////
        fields2.Add("tag");
        types2.Add("string");
        values2.Add("000");
        /////////////////////////////////////////////////

        fields2.Add("field");
        types2.Add("string");
        string vv = fs[0].Replace("MARC Leader", "");
        values2.Add(vv.Trim());
        /////////////new////////////////////
        switchs("000", vv.Trim());
        /////////////////////////////////////////////// 
        foreach (string fx in fs)
        {
            string ff = fx;
            Match match = regex.Match(ff);
            if (match.Groups[1].Value != "")
            {

                tag = match.Groups[1].Value;
                /////////////////////////////////////
                /////////////////////////////////////////

                fields2.Add("tag");
                types2.Add("string");
                values2.Add(tag);

                /////////////////////////////////////////////////
                ff = ff.TrimStart(tag.ToCharArray());

                match = regex2.Match(ff);
                if (match.Groups[1].Value != "")
                {
                    ind = match.Groups[1].Value;

                    ff = ff.TrimStart(ind.ToCharArray());
                    ind = ind.Replace("\t", "");
                    //////////////////////////////
                    fields2.Add("indicator");
                    types2.Add("string");
                    values2.Add(ind);
                    /////////////////////////////////////////////////
                    if (ff.Contains("|"))
                    {
                        string[] mm = ff.Split("|".ToCharArray());

                        string subs = "";
                        field = mm[0];
                        for (int i = 1; i < mm.Length; i++)
                        {
                            subs += mm[i].Substring(0, 1) + "$";
                            mm[i] = mm[i].Replace('"', ' ');
                            mm[i] = mm[i].Replace("'", "");
                            mm[i] = mm[i].Remove(0, 1);
                            //////////////////////////////


                            field += mm[i] + "%";
                        }

                        fields2.Add("subfield");
                        types2.Add("string");
                        values2.Add(subs.TrimEnd('$'));
                        /////////////////////////////////////////////////  
                        //////////////////////////////
                        fields2.Add("field");
                        types2.Add("string");
                        values2.Add(field.TrimEnd('%'));
                        ///////////////////////////////////////////////  
                        switchs(tag, field.Replace('%', ' '));

                    }
                    else
                    {
                        ff = ff.Replace('"', ' ');
                        ff = ff.Replace("'", "");
                        //////////////////////////////
                        //////////////////////////////
                        fields2.Add("field");
                        types2.Add("string");
                        values2.Add(ff);
                        ///////////////////////////////////////////////  
                        switchs(tag, ff);
                        field = ff;
                    }
                }
                else
                {
                    ff = ff.Replace('"', ' ');
                    ff = ff.Replace("'", "");
                    //////////////////////////////
                    //////////////////////////////
                    fields2.Add("field");
                    types2.Add("string");
                    values2.Add(ff);
                    ///////////////////////////////////////////////  
                    switchs(tag, ff);
                    field = ff;

                }

            }

            //Response.Write(tag + "   " + ind + "   " + field);
            //Response.Write("<br />");

        }
        insertion();

    }
    public void form3Mrc(string fs)
    {

       


        FileMARC marcRecords = new FileMARC(fs);

        foreach (Record record in marcRecords)
        {
            int x = marcRecords.Count;
            //Response.Write(record.Leader);
            //Response.Write("<br />");
            fields2.Add("tag");
            types2.Add("string");
            values2.Add("000");
            /////////////////////////////////////////////////

            fields2.Add("field");
            types2.Add("string");
            values2.Add(record.Leader);
            //////////new//////////////////
            switchs("000", record.Leader);
            /////////////////////////////////////////////// 
            foreach (Field fld in record.Fields)
            {
                fields2.Add("tag");
                types2.Add("string");
                values2.Add(fld.Tag);
                /////////////////////////////////////////////////

                if (fld.IsDataField())
                {

                    DataField cc = (DataField)fld;
                    string ind = (cc.Indicator1 + cc.Indicator2).ToString();
                    string subs = "";
                    string field = "";
                    foreach (Subfield sub in cc.Subfields)
                    {
                        subs += sub.Code + "$";
                        field += sub.Data + "%";

                    }
                    field = field.Replace('"', ' ');
                    field = field.Replace("'", "");
                    //////////////////////////////
                    fields2.Add("subfield");
                    types2.Add("string");
                    values2.Add(subs.TrimEnd('$'));
                    /////////////////////////////////////////////////  
                    //////////////////////////////
                    fields2.Add("field");
                    types2.Add("string");
                    values2.Add(field.TrimEnd('%'));
                    ///////////////////////////////////////////////  
                    switchs(fld.Tag, field.Replace('%', ' '));
                }
                else
                {
                    if (fld.IsControlField())
                    {
                        ControlField cc = (ControlField)fld;
                        //////////////////////////////
                        fields2.Add("field");
                        types2.Add("string");
                        values2.Add(cc.Data);
                        ///////////////////////////////////////////////
                        switchs(fld.Tag, cc.Data);
                    }

                }
                /////////////////////////////////////////////// 

                //Response.Write(fld.Tag + "    " + fld.FormatField());
                //Response.Write("<br />");
            }
            insertion();
        }
        marcRecords.Reset();
    }
    public void insertion()
    {


        int f = DB.INSERT2("products", fields, types, values);
        if (f > 0)
        {
            ins(f);
          
            
        }
        if (!string.IsNullOrEmpty(Request.QueryString["poid"]))
        {
            DB.DELETE("pendingobjects", "id", "int", Request.QueryString["poid"]);
            DB.setpendingobjectscash();
        }

    }
public void ins(int f)
{
  //////////////////////////////
    for (int i = 0; i < fields2.Count; i++)
    {
        string inds = "";
        string myfield = "";
        string mytag = "";
        string mysub = "";
        if (fields2[i] == "tag")
        {
            mytag = (string)values2[i];
            if (fields2[i + 1] == "indicator")
            {
                inds = (string)values2[i + 1];
                // DB.INSERTag((string)values2[i], inds, f);
                i++;
                if (fields2[i + 1] == "subfield")
                {
                    mysub = (string)values2[i + 1];
                    i++;
                    if (fields2[i + 1] == "field")
                    {
                        myfield = (string)values2[i + 1];
                        i++;
                    }

                }

                else
                {
                    if (fields2[i + 1] == "field")
                    {
                        myfield = (string)values2[i + 1];
                        i++;
                    }

                }

            }
            else
            {
                if (fields2[i + 1] == "subfield")
                {
                    mysub = (string)values2[i + 1];
                    i++;
                    if (fields2[i + 1] == "field")
                    {
                        myfield = (string)values2[i + 1];
                        i++;
                    }

                }

                else
                {
                    if (fields2[i + 1] == "field")
                    {
                        myfield = (string)values2[i + 1];
                        i++;
                    }

                }

            }

            
            DB.INSERTag(mytag, inds, f, mysub, myfield);
        }

    }




}
public string freqswitch(string vals)
{

    switch (vals)
    {
        case "m":
            vals = "4";
            break;
        case "w":
            vals = "2";
            break;
        case "d":
            vals = "5";
            break;
        case "y":
            vals = "6";
            break;
        default:
            vals = "";
            break;

    }
    return vals;
}
public string freqswitch2(string vals)
{

    
    vals = vals.ToLower();
    if (vals.Contains("monthly"))
    {
        vals = "4";
    }
    else
    {
        if (vals.Contains("weekly"))
        {
            vals = "2";
        
        }
        else
        {
            if (vals.Contains("daily"))
            {
                vals = "5";
            }
            else
            {
                if (vals.Contains("yearly"))
                {

                    vals = "6";
                }
                else
                {
                    vals = "";
                }
            
            }
        }
    }
    //switch (vals.ToLower())
    //{
    //    case "monthly":
    //        vals = "4";
    //        break;
    //    case "weekly":
    //        vals = "2";
    //        break;
    //    case "daily":
    //        vals = "5";
    //        break;
    //    case "yearly":
    //        vals = "6";
    //        break;
    //    default:
    //        vals = "";
    //        break;

    //}
    return vals;
}
    public void switchs(string tag, string val)
    {



        switch (tag)
        {
           
            case "000":
                //// / //////auther////////////////////////////
              
                    if (!fields.Exists(element => element == "product_type_id"))
                    {
                        string vals = "";
                      val= val.Substring(7,1);
                      vals = val == "s" ? "2" : "1";

                      fields.Add("product_type_id");
                      types.Add("int");
                      values.Add(vals);
                        /////////////
                }
                break;
            /////////////////////////////////////////////////
            case "008":
                //// / //////freq////////////////////////////

                if (!fields.Exists(element => element == "freq_id"))
                {
                    string vol = "";
                    val = val.Trim();
                    val = val.Substring(18, 1);
                    vol = freqswitch(val);
                    if (vol != "")
                    {
                        fields.Add("freq_id");
                        types.Add("int");
                        values.Add(vol);
                        ///////////////
                    }
                }
                break;
                ////////////////////////////////////////////////
            case "310":
                //// / //////freq////////////////////////////

                if (!fields.Exists(element => element == "freq_id"))
                {
                    string vol = "";
                    val = val.Trim();
                   // val = val.Split(' ').First(element => element.Contains("ly"));
                    vol = freqswitch2(val);
                    if (vol != "")
                    {
                        fields.Add("freq_id");
                        types.Add("int");
                        values.Add(vol);
                        ///////////////
                    }
                }
                break;
                ////////////////////////////////
            case "100":
                //// / //////auther////////////////////////////
                if (auther == "")
                {
                    fields.Add("auther1");
                    types.Add("string");
                    values.Add(val);
                    auther = val;
                }
                /////////////////////////////////////////////////
                break;
            ////////isbn//////////
            case "020":
                //////////////////
                if (issn == "")
                {

                    fields.Add("issn");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    //////////////////
                    if (!fields.Exists(element => element == "product_type_id"))
                    {
                        fields.Add("product_type_id");
                        types.Add("int");
                        values.Add(1);
                        ///////////////
                    }
                    issn = val;
                }
                break;
            //////issn//////
            case "022":
                //////////////////
                if (issn == "")
                {

                    fields.Add("issn");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    //////////////////
                    if (!fields.Exists(element => element == "product_type_id"))
                    {
                        fields.Add("product_type_id");
                        types.Add("int");
                        values.Add(2);
                        ///////////////
                    }
                    issn = val;
                }
                break;
            //////congress//////
            case "050":
                //////////////////
                if (lc == "")
                {

                    fields.Add("lc");
                    types.Add("string");
                    values.Add(val);
                    ///////////////

                    lc = val;
                }
                break;
            //////dewey//////
            case "082":
                //////////////////
                if (dwoy == "")
                {

                    fields.Add("dwoy");
                    types.Add("string");
                    values.Add(val);
                    ///////////////

                    dwoy = val;
                }
                break;
            case "240":
                ////////title//////////
                if (title == "")
                {
                    fields.Add("product");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    title = val;
                }
                break;
            ///////title///////////
            case "245":
                if (title == "")
                {
                    //////////////////
                    fields.Add("product");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    title = val;
                }
                break;
            ///////title//////////
            case "222":
                if (title == "")
                {
                    //////////////////
                    fields.Add("product");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    title = val;
                }
                break;
            case "650":
                //////////////////
                if (topic == "")
                {
                    fields.Add("topic");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    topic = val;
                }
                break;
            //////desc////////
            case "500":
                //////////////////
                if (desc == "")
                {
                    fields.Add("productdesc");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    desc = val;
                }
                break;
            /////////desc///////
            case "504":
                //////////////////
                if (desc == "")
                {
                    fields.Add("productdesc");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    desc = val;
                }
                break;
            /////////desc///////
            case "505":
                //////////////////
                if (desc == "")
                {
                    fields.Add("productdesc");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    desc = val;
                }
                break;
            /////////desc///////
            case "530":
                //////////////////
                if (desc == "")
                {
                    fields.Add("productdesc");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    desc = val;
                }
                break;
            /////////desc///////
            case "590":
                //////////////////
                if (desc == "")
                {
                    fields.Add("productdesc");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    desc = val;
                }
                break;
            case "260":
                if (pups == "")
                {
                    //////////////////
                    fields.Add("publisher");
                    types.Add("string");
                    values.Add(val);
                    ///////////////
                    pups = val;
                }
                break;
            ////////////////////////
            default:


                break;
        }



    }

    public void cols(string paths)
    {
        string[] fs = File.ReadAllLines(paths, System.Text.Encoding.GetEncoding("UTF-8"));


        Regex regex3 = new Regex("^(=*)");
        Regex regex4 = new Regex("(MARC)");

        Match match = regex3.Match(fs[0]);
        if (match.Groups[1].Value != "")
        {
            form1Mrc(fs);

        }
        else
        {
            match = regex4.Match(fs[0]);
            if (match.Groups[1].Value != "")
            {
                form2Mrc(fs);
            }
            else
            {
                if (fs.Length == 1)
                {

                    form3Mrc(fs[0]);
                }

            }
        }
        //Response.Redirect("~/NewProduct.aspx");
    
    }
    protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        if (AsyncFileUpload1.HasFile)
        {
            
            string paths = Server.MapPath(Request.ApplicationPath) + "\\marcfiles\\" + AsyncFileUpload1.FileName;

            AsyncFileUpload1.SaveAs(paths);
         //   AsyncFileUpload1.ClearAllFilesFromPersistedStore();
         

          



        }
    
    }
    protected void end_Click(object sender, EventArgs e)
    {
        try
        {
            string bb = Server.MapPath(Request.ApplicationPath) + "\\marcfiles\\" + AsyncFileUpload1.FileName;
            cols(bb);
            Response.Redirect("~/NewProduct.aspx");
        }
        catch (Exception ex)
        {
            
        }

    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    e.Row.Attributes.Add("onmouseover", "this.Mystyle=this.style.backgroundColor;this.style.backgroundColor='#FFFFA8'");

        //    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.Mystyle");
        //}
    }
   
    

    public void insertfld(string tag, string ins, string flds)
    {

        //////////////////////////////
        fields2.Add("tag");
        types2.Add("string");
        values2.Add(tag);
        ///////////////////////////////////////////////
        //////////////////////////////
        fields2.Add("indicator");
        types2.Add("string");
        values2.Add(ins);
        ///////////////////////////////////////////////
        //////////////////////////////
        fields2.Add("field");
        types2.Add("string");
        values2.Add(flds);
        ///////////////////////////////////////////////
        //////////////////////////////
    }


    protected void save_Click(object sender, EventArgs e)
    {
        insertfld("000", "", leader.Text);
        insertfld("008", "", fix.Text);
        //////////////////////////////
        switchs("050", lcs.Text);
        insertfld("050", "", lcs.Text);
        /////////////////////////////////////
        //////////////////////////////
        switchs(DropDownList1.SelectedItem.Text.Split(',')[1], isn.Text);
        insertfld(DropDownList1.SelectedItem.Text.Split(',')[1], "", isn.Text);
        /////////////////////////////////////
        switchs("082", dewey.Text);
        insertfld("082", "", dewey.Text);
        ///////////////////////////////////
        switchs("260", pup.Text);
        insertfld("260", "", pup.Text);
        /////////////////////////////
        switchs("100", auth.Text);
        insertfld("100", "", auth.Text);
        //////////////////////////////////////
      //  insertfld("035", "", f35.Text);
        //////////////////////////////
        switchs("245", address.Text);
        insertfld("245", "", address.Text);
        /////////////////////////////////////////
        insertfld("300", "", f300.Text);
        ////////////////////////////////////////
        /////////////////////////////////////////
       // insertfld("310", "", f310.Text);
        insertfld("310", "", DropDownList2.SelectedValue);
        //////////////////
        fields.Add("freq_id");
        types.Add("int");
        values.Add(DropDownList2.SelectedValue);
        ///////////////
        //////////////////
        fields.Add("classification_id");
        types.Add("int");
        values.Add(DropDownList3.SelectedValue);
        ///////////////
        //////////////////
        fields.Add("puplisher_id");
        types.Add("int");
        values.Add(DropDownList5.SelectedValue);
        ///////////////
        //////////////////////
        //fields.Add("product_type_id");
        //types.Add("int");
        //values.Add(DropDownList1.SelectedValue);
        ///////////////////
        //////////////////////////////////////////
        /////////////////////////////////////////
        insertfld("005", "", f005.Text);
        ////////////////////////////////////////
        switchs("650", topics.Text);
        insertfld("650", "", topics.Text);
        //////////////////////////////////////
        switchs("500", notes.Text);
        insertfld("500", "", notes.Text);
        // //////////////////////////////
        //"SELECT [id], [product], [productdesc], [publisher], [topic], [product_type_id], [issn], [dwoy], [lc], [auther1] FROM [products] "
        if (Grid1.AddedItems.Length > 0)
        {
            for (int i = 0; i < Grid1.AddedItems.Length; i++)
            {
                if ((Grid1.AddedItems[i].Cells[3].Value != null) && (Grid1.AddedItems[i].Cells[1].Value != null))
                {
                    string tag = Grid1.AddedItems[i].Cells[3].Value.ToString();
                    string ins = (Grid1.AddedItems[i].Cells[2].Value.ToString() == null ? "" : Grid1.AddedItems[i].Cells[2].Value.ToString());
                    string fd = Grid1.AddedItems[i].Cells[1].Value.ToString();
                    insertfld(tag, ins, fd);
                }
            }
        }
        if (ViewState["aoe"].ToString() == "0")
        {
           insertion();
        }
        else
        {
            DB.DELETE("tags", "int,product_id," + ViewState["aoe"].ToString());
            DB.UPDATE("products", "int,id," + ViewState["aoe"].ToString(), fields, types, values);
            ins(int.Parse(ViewState["aoe"].ToString()));;

        }

        Response.Redirect("~/NewProduct.aspx");

    }
    protected void newhands_Click(object sender, EventArgs e)
    {
        ViewState["aoe"] = "0";
    
        Grid1.DataSource = new DataTable();
        Grid1.DataBind();
        Page.ClientScript.RegisterStartupScript(this.GetType(), "reports", "there();", true);


         
    }

    protected void newupload_Click(object sender, EventArgs e)
    {
       
        Page.ClientScript.RegisterStartupScript(this.GetType(), "reports", "there3();", true);



    }
    protected void act_SelectedIndexChanged(object sender, EventArgs e)
    {
        SqlDataSource1.SelectCommand = "select p.*,t.product_type from  products p INNER JOIN product_types t ON t.id = p.product_type_id where  p.product_type_id =" + act.SelectedValue + "  Order BY p.id desc";

      
        //GridView1.DataSource = SqlDataSource1;
        ListView1.DataBind();
    }
    protected void allcompanies_SelectedIndexChanged(object sender, EventArgs e)
    {
        SqlDataSource1.SelectCommand = "select p.*,t.product_type from  products p INNER JOIN product_types t ON t.id = p.product_type_id where  classification_id =" + allcompanies.SelectedValue + "  Order BY p.id desc";

        ListView1.DataBind();
        
    }
    protected void searchfield_TextChanged(object sender, EventArgs e)
    {
        string txt = DB.remove_spaces(searchfield.Text);
        SqlDataSource1.SelectCommand = "select p.*,t.product_type from  products p INNER JOIN product_types t ON t.id = p.product_type_id WHERE product  LIKE '%" + searchfield.Text + "%'  Order BY p.id desc";
        ListView1.DataBind();
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
         string txt = DB.remove_spaces(searchfield.Text);
         if (DropDownList4.SelectedValue == "0")
         {
             SqlDataSource1.SelectCommand = "select p.*,t.product_type from  products p INNER JOIN product_types t ON t.id = p.product_type_id WHERE product  LIKE '%" + searchfield.Text + "%'  Order BY p.id desc";
         }
         else
         {
             SqlDataSource1.SelectCommand = "select p.*,t.product_type from  products p INNER JOIN product_types t ON t.id = p.product_type_id WHERE " + DropDownList4.SelectedValue + "  LIKE '%" + searchfield.Text + "%'  Order BY p.id desc";
         }

         ListView1.DataBind();
    }
    protected void ImageButton1_Click(object sender, EventArgs e)
    {
        string txt = DB.remove_spaces(searchfield.Text);
        if (DropDownList4.SelectedValue == "0")
        {
            SqlDataSource1.SelectCommand = "select p.*,t.product_type from  products p INNER JOIN product_types t ON t.id = p.product_type_id WHERE product  LIKE '%" + searchfield.Text + "%'  Order BY p.id desc";
        }
        else
        {
            SqlDataSource1.SelectCommand = "select p.*,t.product_type from  products p INNER JOIN product_types t ON t.id = p.product_type_id WHERE " + DropDownList4.SelectedValue + "  LIKE '%" + searchfield.Text + "%'  Order BY p.id desc";
        }

        ListView1.DataBind();
    }
    protected void newsub_Click(object sender, EventArgs e)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "reports", "there4();", true);
    }
   
    protected void Listview1_ItemCommand(object sender , ListViewCommandEventArgs e)
    {
        if (e.CommandName != "Page")
        {

            if (e.CommandName == "show")
            {

                int ff = int.Parse((e.CommandArgument).ToString());
                //MARCDetails mr = (MARCDetails)((LinkButton)e.CommandSource).NamingContainer.FindControl("MARCDetails1");
                MARCDetails1.setMarc(DB.getMarc(ff));
                Page.ClientScript.RegisterStartupScript(this.GetType(), "hj", "there2();", true);
                //ScriptManager.RegisterStartupScript(this, this.GetType(), "reports", "there2();", true);
            }
            if (e.CommandName == "edit")
            {

                //  int ff = int.Parse((e.CommandArgument).ToString());

                DataSet ds = DB.getMarc(e.CommandArgument.ToString());
                ViewState["aoe"] = e.CommandArgument.ToString();

                if (ds.Tables[0].Rows[0]["product_type_id"].ToString() != null)
                {
                    string bb = ds.Tables[0].Rows[0]["product_type_id"].ToString();
                    ListItem ls = DropDownList1.Items.FindByValue(bb);
                    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(ls);

                }
                if (ds.Tables[0].Rows[0]["freq_id"].ToString() != null)
                {
                    DropDownList2.SelectedIndex = DropDownList2.Items.IndexOf(DropDownList2.Items.FindByValue(ds.Tables[0].Rows[0]["freq_id"].ToString()));

                }
                if (ds.Tables[0].Rows[0]["classification_id"].ToString() != null)
                {
                    DropDownList3.SelectedIndex = DropDownList3.Items.IndexOf(DropDownList3.Items.FindByValue(ds.Tables[0].Rows[0]["classification_id"].ToString()));

                }
                if (ds.Tables[0].Rows[0]["puplisher_id"].ToString() != null)
                {
                    DropDownList5.SelectedIndex = DropDownList5.Items.IndexOf(DropDownList5.Items.FindByValue(ds.Tables[0].Rows[0]["puplisher_id"].ToString()));

                }
                /////////////////////////////////////////////
                isn.Text = ds.Tables[0].Rows[0]["issn"].ToString();
                dewey.Text = ds.Tables[0].Rows[0]["dwoy"].ToString();
                pup.Text = ds.Tables[0].Rows[0]["publisher"].ToString();
                auth.Text = ds.Tables[0].Rows[0]["auther1"].ToString();
                address.Text = ds.Tables[0].Rows[0]["product"].ToString();
                notes.Text = ds.Tables[0].Rows[0]["productdesc"].ToString();
                lcs.Text = ds.Tables[0].Rows[0]["lc"].ToString();
                topics.Text = ds.Tables[0].Rows[0]["topic"].ToString();
                DataRow[] dro = ds.Tables[1].Select("tag='000'");
                if (dro.Length > 0)
                {
                    leader.Text = dro[0]["field"].ToString();
                    dro = ds.Tables[1].Select("tag='008'");
                    if (dro.Length > 0)
                        fix.Text = dro[0]["field"].ToString();
                }
                //dro = ds.Tables[1].Select("tag='035'")[0];
                // if(dro!=null)
                //f35.Text = dro["field"].ToString();

                dro = ds.Tables[1].Select("tag='300'");
                if (dro.Length > 0)
                    f300.Text = dro[0]["field"].ToString();
                ////////////////////////////////////////////////////////

                //////////////////////////////////////////
                Grid1.DataSource = ds.Tables[1];
                Grid1.DataBind();
                ////////////////////////////////////////////

                //ScriptManager.RegisterStartupScript(this, this.GetType(), "hj", "there();", true);

                Page.ClientScript.RegisterStartupScript(this.GetType(), "hj", "there();", true);


            }
            if (e.CommandName == "delete")
            {
                int ff = int.Parse((e.CommandArgument).ToString());
                DB.DELETE("products", "int,id," + ff);
                DB.DELETE("tags", "int,product_id," + ff);
                // GridView1.DataBind();
                Response.Redirect("~/NewProduct.aspx");
            }
        }
    
    }
    
}
